package com.app.mymvp.business.search;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.app.mymvp.base.BaseActivity;
import com.app.mymvp.entity.SearchHistoryEntity;
import com.app.mymvp.utils.projectutils.RecordSQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ${Bi} on 2016/10/13 11:13.
 */

public class SearchModel implements SearchContract.Model{

    private RecordSQLiteOpenHelper helper;
    private SQLiteDatabase db;

    @Override
    public boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }


    @Override
    public void deleteData() {

        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    @Override
    public void deleteOneData(String historyName) {
        db = helper.getWritableDatabase();
        db.delete("records", "name=?", new String[]{historyName});
        db.close();
    }

    @Override
    public List<SearchHistoryEntity> queryData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
        List<SearchHistoryEntity> searchHistoryEntities=new ArrayList<>();
        SearchHistoryEntity searchHistoryEntity;
        searchHistoryEntities.clear();
        while (cursor.moveToNext()) {
            searchHistoryEntity = new SearchHistoryEntity();
            searchHistoryEntity.setHistoryName(cursor.getString(cursor.getColumnIndex("name")));
            searchHistoryEntities.add(searchHistoryEntity);
        }

     return searchHistoryEntities;
    }

    @Override
    public void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

    @Override
    public void initDatebase(Context context) {
        helper = new RecordSQLiteOpenHelper(context);
    }
}
